package com.lwj.service.system;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lwj.dto.system.DefListDto;
import com.lwj.dto.system.DictionaryDefDto;
import com.lwj.mapper.system.DictionaryDefMapper;
import com.lwj.model.system.DictionaryCategory;
import com.lwj.model.system.DictionaryDef;
import com.lwj.service.DozerService;
import com.lwj.vo.PageBean;
import com.lwj.vo.system.DictionaryDefVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictionaryDefServiceImpl implements DictionaryDefService {
    @Autowired
    private DictionaryDefMapper dictionaryDefMapper;
    @Autowired
    private DozerService dozerService;
    @Autowired
    private DictionaryCategoryService dictionaryCategoryService;

    @Override
    public PageBean<DictionaryDefVo> defList(DefListDto dto) {
        Page<DictionaryDefVo> objects = PageHelper.startPage(dto.getPageNumber(), dto.getPageSize());
        dictionaryDefMapper.defList(dto);
        return PageBean.page(objects);
    }

    @Override
    public int saveDef(DictionaryDefDto dto) {
        DictionaryDef def = dozerService.map(dto, DictionaryDef.class);
        Integer result;
        if(StringUtils.hasText(dto.getDefId())){
            result= dictionaryDefMapper.updateByPrimaryKeySelective(def);
        }else {
            List<DictionaryDefVo> defVos = getByCategoryId(def.getCategoryId());
            def.setSortNum(defVos.size()+2);
            String defCode = getDefCode(defVos, def.getCategoryId());
            def.setDefCode(defCode);
            result= dictionaryDefMapper.insertSelective(def);
        }
        return result;
    }
    public String getDefCode( List<DictionaryDefVo> defVos ,String categoryId){
        DictionaryCategory category = dictionaryCategoryService.selectByPrimaryKey(categoryId);
        String categoryCode = category.getCategoryCode();
        if(CollectionUtils.isEmpty(defVos)){
            return categoryCode+"01";
        }else {
            DictionaryDefVo dictionaryDefVo = defVos.get(0);
            int i = Integer.parseInt(dictionaryDefVo.getDefCode().replace(categoryCode, ""));
            categoryCode+=i>9?"0"+i:i;
            return categoryCode+i;

        }
    }
    @Override
    public List<DictionaryDefVo> getByCategoryId(String categoryId) {
        return dictionaryDefMapper.getByCategoryId(categoryId);
    }

    @Override
    public List<DictionaryDefVo> getByCategoryCode(String categoryCode) {
        return dictionaryDefMapper.getByCategoryCode(categoryCode);
    }
}
